﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Configuration;
using System.Data.SqlClient;
using PetShop.DBUtility;
using System.Data;

public class CacheManager
{
    // 获取数据库中信息
    public static List<Product> Products
    {
        get
        {
            // 首先通过缓存读取
            HttpContext context = HttpContext.Current;

            List<Product> list = context.Cache["Products"] as List<Product>;
            if (list == null)
            {
                // 从数据库读取
                string connectionString = ConfigurationManager.ConnectionStrings["northwind"].ConnectionString;
                // 查询数据
                string sql = "select productname, description from view_product";

                using (SqlDataReader reader = SqlHelper.ExecuteReader(
                    connectionString,
                    CommandType.Text,
                    sql))
                {
                    list = new List<Product>();
                    while (reader.Read())
                    {
                        Product p = new Product();
                        p.Name = reader.GetString(0);
                        p.Description = reader.GetString(1);
                        list.Add(p);
                    }
                }

                // 保存到缓存中

                // 此时依赖于多个对象

                // SQL 依赖对象, 一定要注意表名的大小写, 必须与创建缓存时写的表名一致
                System.Web.Caching.SqlCacheDependency product
                    = new System.Web.Caching.SqlCacheDependency(
                        "northwindcache",
                        "products");

                System.Web.Caching.SqlCacheDependency category
                    = new System.Web.Caching.SqlCacheDependency(
                        "northwindcache",
                        "categories");

                // 多个缓存依赖需要组合成一个依赖对象使用
                System.Web.Caching.AggregateCacheDependency acd
                    = new System.Web.Caching.AggregateCacheDependency();
                acd.Add(product, category);

                // 创建 SQL 缓存
                context.Cache.Add(
                    "Products",
                    list,
                    acd,
                    System.Web.Caching.Cache.NoAbsoluteExpiration,
                    new TimeSpan(1, 0, 0),
                     System.Web.Caching.CacheItemPriority.Normal,
                     new System.Web.Caching.CacheItemRemovedCallback(Callback)
                );

            }

            return list;
        }
    }
    private static void Callback(
        string key,
        Object value,
        System.Web.Caching.CacheItemRemovedReason reason    // 原因
        )
    {
        // 但是,需要注意的是,此时不一定有请求
        // 因此,不能使用 HttpContext

        // 如果需要使用 Cache 
        // 通过 System.Web.HttpRuntime.Cache 来获取当前网站应用程序的 Cache
    }
}
